import { RouteLocationNormalizedLoaded, useRoute } from 'vue-router'
import { type Runnable } from '@/typings'
import { watch } from 'vue'

interface PageTabHandler {
  /** 页面被激活时调用的回调函数 */
  activeHandler?: Runnable
  /** 页面失活时调用的回调函数 */
  inactiveHandler?: Runnable
  /** 是否立即执行回调 */
  immediate?: boolean
}

let route: RouteLocationNormalizedLoaded
export class PageTabHelper {
  private _currentPath: string
  private _activeHandler?: Runnable
  private _inactiveHandler?: Runnable

  constructor(args?: PageTabHandler) {
    if (!route) {
      route = useRoute()
    }
    console.log(route.path)
    this._currentPath = route.path
    this._activeHandler = args?.activeHandler
    this._inactiveHandler = args?.inactiveHandler
    watch(
      () => route.path,
      (value, oldValue) => {
        if (value === this._currentPath && oldValue !== this._currentPath) {
          this._activeHandler?.()
        } else if (oldValue === this._currentPath && value !== this._currentPath) {
          this._inactiveHandler?.()
        }
      },
      {
        immediate: args?.immediate,
      }
    )
  }
  set activeHandler(activeHandler: Runnable) {
    this._activeHandler = activeHandler
  }
  set inactiveHandler(inactiveHandler: Runnable) {
    this._inactiveHandler = inactiveHandler
  }
}
